﻿var ToolBarConfig = {
    File: {
        description: '文件 ',
        Items: {
            //Create: {id: 'Create', img: 'create.png', tag: '创建'},
            Save: {id: 'Save', img: 'save.png', tag: '保存'},
            //Open: {id: 'Open', img: 'open.png', tag: '打开'},
            Import: {id: 'Import', img: 'import.png', tag: '导入'},
            Export: {id: 'Export', img: 'export.png', tag: '导出'}
        }
    },

    Edit: {
        description: '编辑',
        Items: {
            Undo: {id: 'Undo', img: 'undo.png', tag: '撤销'},
            Redo: {id: 'Redo', img: 'redo.png', tag: '重做'},
            Lock: {id: 'lock', img: 'lock.png', tag: '加锁'}
            //,
            //Paste: { id: 'Paste', tag: '粘贴' },
            //Delete: { id: 'Delete', tag: '删除' }
        }
    },


    Activity: {
        description: '节点',
        Items: {
            Approval: {id: 'Approval', img: 'approval.png', tag: '人工活动'},
            Branching: {id: 'Branching', img: 'branching.png', tag: '分支合并'},
            Condition: {id: 'Condition', img: 'condition.png', tag: '条件'},
            Freedom: {id: 'Freedom', img: 'freedom.png', tag: '自由活动'}/*,
             Subprocesses: { id: 'Subprocesses', tag: '子流程' }*/
        }
    }
}

ToolBar = {
    CanOperation: false,
    lockImage: null,
    islock: false,
    saveLayer: null,
    InitialToolBar: function () {
        var me = this;
        $.each(ToolBarConfig, function (j, menu) {
            var toolBar = $("#toolBar");
            var j = 0;
            $.each(menu.Items, function (i, val) {
                var image = $("<img>").css({
                    "height": "24px",
                    "width": "auto",
                    "margin-top": "2px"
                }).attr({"src": "/assets/js/workflow/images/toolbar/" + val.img, "title": val.tag});
                var toolBarItem = $("<div>").attr("class", "divItem").mouseover(function () {
                    toolBarItem.css({"background-color": "#ffefbb", "border": "1px solid #e5c365"});
                }).mouseout(function () {
                    toolBarItem.css({"background-color": "transparent", "border": "0px solid transparent"});
                }).mousedown(function () {
                    toolBarItem.css({"background-color": "#fdf6de", "border": "1px solid #e5c365"});
                    isDoubleClickCommand = false;
                    me.mousedownCallBack(i, image);
                }).dblclick(function () {
                    isDoubleClickCommand = true;
                    me.mousedownCallBack(i, image);
                })
                if (Command[i] == Command.Lock)
                    me.lockImage = image;
                var jss = val.js;


                toolBarItem.append(image);
                toolBar.append(toolBarItem)
                ++j;
            });

            var split = $("<div>").attr("class", "divSplit");
            toolBar.append(split);


        });
    },

    mousedownCallBack: function (command, image) {
        var me = this;
        var tmp = Command.Create;
        if (command in Command)
            tmp = Command[command];
        if (tmp == Command.Create || tmp == Command.Open || tmp == Command.Export || tmp == Command.Import) {
            switch (Command[command]) {
                case Command.Create:
                    me.Create();
                    break;
                case Command.Open:
                    me.Open();
                    break;
                case Command.Import:
                    me.Import();
                    break;
            }
        }


        if (me.CanOperation) {
            if (command in ActivityType) {

                gcommand = Command.AddActivity;
                currentActivityType = ActivityType[command];
                $("#divWorkspace").css("cursor", "crosshair");


            }

            else {
                switch (Command[command]) {
                    case Command.AddRules:
                        gcommand = command;
                        break;
                    case Command.Save:
                        SqlHelper.GetAllPackage(me.Save);
                        break;
                    case Command.Lock:

                        me.Edit(image);
                        break
                    case Command.Undo:
                        me.UndoCommand();
                        break;
                    case Command.Redo:
                        me.RedoCommand();
                        break;
                    case Command.Export:
                        me.Export();
                        break;

                }


            }
        }
    },

    Create: function (templateId) {
        var me = this;
        var layerNum = $.layer({
            type: 1,
            title: false,
            move: [$("#divorgTitle"), true],
            fix: false,
            closeBtn: true,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['360px', '420px'],
            page: {dom: $("#divOrg")},
            success: function () {
            }
        });
        $(".xubox_main").css("background-color", "transparent");
        OrgHelper.BindOrg(SqlHelper.OrgList);
        $("#btnCreateOK").unbind();
        $("#btnCreateCancel").unbind();
        $("#btnCreateOK").click(function () {

            var nodes = zTreeObj.getSelectedNodes();
            if (nodes.length > 0) {
                OrgID = nodes[0].id;
                SqlHelper.GetAllJob();
                canvasHelper.CreateTemplate();
                layer.close(layerNum);
                me.CanOperation = true;
                me.UnBind();

                //myCanvas.unbind();
                //myCanvas.dblclick(function (e) {
                //    e.stopPropagation();
                //    mouseOperation.leftbuttondoubleclick(e);

                //});

                me.BindEvent();
                templateStatus = TemplateStatus.New;
                template = {id: templateId ? templateId : undefined};
                $("#divTemplateName").css('display', 'none');
            }
        });
        $("#btnCreateCancel").click(function () {
            layer.close(layerNum);
        });

    },

    Save: function (data) {
        var me = ToolBar;
        $("#selectPackage").html("");
        $("#btnNewVersion").unbind();
        $("#btnEdit").unbind();
        $("#btnSaveOK").unbind();
        $("#btnSaveCancel").unbind();


        var package_id = template == undefined || template.id == undefined || template.id == null ? "" : template.id;


        $.each(data, function (i, val) {
            var option = package_id == val.id ? $("<option selected='selected'  value='" + val.id + "' >" + val.packageName + "</option>") : $("<option  value='" + val.id + "' >" + val.packageName + "</option>");
            $("#selectPackage").append(option);
        });

        var tmpName = template == undefined || template.templateName == undefined || template.templateName == null ? "" : template.templateName;
        $("#txtTEMPLATE_NAME").val(tmpName);
        var description = template == undefined || template.description == undefined || template.description == null ? "" : template.description;
        $("#txtDESCRIPTION").val(description);

        $("#txtImg").val(template.imgurl || "");
        $("#txtTEMPLATE_NAME").val(tmpName);
        me.saveLayer = $.layer({
            type: 1,
            title: false,
            move: [$("#divSaveTitle"), true],
            fix: false,
            closeBtn: false,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['650px', '300px'],
            page: {dom: $("#divSave")},
            success: function () {
            }
        });


        $("#btnSaveCancel").click(function () {
            layer.close(me.saveLayer);
        });

        $(".xubox_main").css("background-color", "transparent");
        switch (templateStatus) {
            case TemplateStatus.New:
                $("#btnNewVersion").css("display", "none");
                $("#btnEdit").css("display", "none");
                $("#btnSaveOK").click(function () {
                    template.guid = Guid.NewGuid();
                    template.publisType = 0;
                    me.SaveInvoke();
                });
                break;
            case TemplateStatus.Open:
                $("#btnNewVersion").css("display", "inline");
                $("#btnEdit").css("display", "inline");
                $("#btnNewVersion").click(function () {
                    template.publisType = 2;
                    me.ChangeID();
                    me.SaveInvoke();

                });
                $("#btnEdit").click(function () {
                    if (confirm('修改当前版本可能导致监控图显示不正确,是否继续？')) {
                        template.publisType = 1;
                        me.SaveInvoke();
                    }
                });
                $("#btnSaveOK").click(function () {
                    template.guid = Guid.NewGuid();
                    template.publisType = 0;
                    me.ChangeID();
                    me.SaveInvoke();
                });

                break;
            case TemplateStatus.Import:
                $("#btnNewVersion").css("display", "none");
                $("#btnEdit").css("display", "none");
                $("#btnNewVersion").click(function () {
                    me.ChangeID();
                    me.SaveInvoke('Workflow_AddTemplate');
                });
                $("#btnEdit").click(function () {
                    me.ChangeID();
                    template.versionNum += 1;
                    me.SaveInvoke('Workflow_UpdateTemplate');
                });
                $("#btnSaveOK").click(function () {

                    template.versionNum = 0;
                    me.ChangeID();
                    me.SaveInvoke('Workflow_AddTemplate');
                });

                break;
        }
    },

    //调用保存
    SaveInvoke: function () {
        var me = ToolBar;
        $.each(activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        activityHelper.GetReturnActivitys(activityHelper.DraftingActivity);
        var result = {
            result: true,
            errorMessage: ''
        }
        $.each(activityHelper.Activitys, function (i, val) {
            var tmp = val.Validate(activityHelper.DraftingActivity, activityHelper.EndActivity);
            if (!tmp.result) {
                result.result = false;
                result.errorMessage += tmp.errorMessage;
            }
        });

        if (result.result) {
            if (template.versionId == undefined) {
                template.versionId = template.id;
                template.versionNum = 0;
            }
            template.packageId = $("#selectPackage option:selected").val();
            template.orgId = OrgID;
            template.templateName = $("#txtTEMPLATE_NAME").val();
            template.description = $("#txtDESCRIPTION").val();
            template.imgurl = $("#txtImg").val();
            var jsonString = me.Snapshot(template);
            $.request('/workflow/template/publish', template, function () {
                alert("成功");
                templateStatus = TemplateStatus.Open;

                SqlHelper.GetAllTemplate({packageName: '', id: ''});
                if (me.saveLayer != undefined && me.saveLayer != null) {
                    layer.close(me.saveLayer);
                }

            });

        }
        else {
            alert(result.errorMessage);
        }
    },

    //初始化快照堆栈
    InitailSnapshot: function () {

        HistroyOpertion = new Array();
        NextOpertion = new Array();
        ToolBar.HistroyOpertion();
    },

    //快照
    Snapshot: function (temp) {

        temp.activities = new Array();
        temp.rules = new Array();
        temp.orgId = OrgID;
        $.each(activityHelper.Activitys, function (i, val) {
            val.ActivityProperty.coordinate = val.position.X + "$" + val.position.Y
            if (val.ActivityProperty.finishNumber == undefined || val.ActivityProperty.finishNumber == '')
                val.ActivityProperty.finishNumber = 0;
            temp.activities.push(val.ActivityProperty);
            val.ActivityProperty.templateGuid = template.guid;
            if (val.ActivityProperty.WF_RULE != undefined && val.ActivityProperty.WF_RULE.length > 0) {
                $.each(val.ActivityProperty.WF_RULE, function (j, rule) {
                    rule.templateGuid = template.guid;
                    temp.rules[temp.rules.length] = rule;
                })
            }
            if (val.activityType == ActivityType.Merging)
                val.ActivityProperty.branchActivityId = val.BranchingControl.guid;


        });
        $.each(rules, function (i, val) {
            var postionX = val.Points[0].X;
            var postionY = val.Points[0].Y;
            for (i = 1; i < val.Points.length; i++) {
                postionX += "$" + val.Points[i].X;
                postionY += "$" + val.Points[i].Y;
            }
            val.RuleProperty.templateGuid = template.guid;
            val.RuleProperty.fromGuid = val.startActivity.guid;
            val.RuleProperty.toGuid = val.endActivity.guid;
            val.RuleProperty.coordinate = postionX + "," + postionY;
            temp.rules[temp.rules.length] = val.RuleProperty;
        });

        var jsonString = $.toJSON(temp);
        return jsonString;
    },

    ChangeID: function () {
        template.guid = Guid.NewGuid();
        $.each(activityHelper.Activitys, function (i, val) {
            val.ChangeID();
        });
        $.each(rules, function (i, val) {
            val.ChangeID();
        });
    },

    Open: function () {
        var me = this;
        var layerNum = $.layer({
            type: 1,
            title: false,
            move: [$("#divOpenTitle"), true],
            fix: false,
            closeBtn: true,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['750px', '400px'],
            page: {dom: $("#divOpen")},
            success: function () {
            }
        });
        $(".xubox_main").css("background-color", "transparent");
        OrgHelper.BindOrgForOpen(SqlHelper.OrgList);


        $("#btnOpenOK").unbind();
        $("#btnOpenCancel").unbind();
        $("#btnOpenOK").click(function () {
            if (openTemplateId == undefined || openTemplateId == null || openTemplateId.length == 0) {
                alert("请选择一个模板！");
                return;
            }

            divMask.css("display", "block");
            layer.close(layerNum);
            setTimeout(me.Wait, 100);

        })
        $("#btnOpenCancel").click(function () {
            layer.close(layerNum);
        })
    },


    Wait: function () {

        var me = this;
        template = SqlHelper.GetTemplateById(openTemplateId);
//编辑
        if (template.activities) {
            OrgID = template.orgId;
            SqlHelper.GetAllJob();
            ToolBar.Load(template);

            ToolBar.CanOperation = true;
            ToolBar.islock = false;
            ToolBar.Edit(undefined);
            templateStatus = TemplateStatus.Open;
            openTemplateId = null;
            ToolBar.InitailSnapshot();
            divMask.css("display", "none");
        } else {
            //新增
            OrgID = app.baseorgId;
            SqlHelper.GetAllJob();
            canvasHelper.CreateTemplate();

            me.CanOperation = true;
            me.UnBind();

            //myCanvas.unbind();
            //myCanvas.dblclick(function (e) {
            //    e.stopPropagation();
            //    mouseOperation.leftbuttondoubleclick(e);

            //});

            me.BindEvent();
            templateStatus = TemplateStatus.New;
            template = pageParm.template;
            template.insert = false;
            $("#divTemplateName").css('display', 'none');
        }
    },

    Edit: function (image) {
        var me = this;
        if (image == undefined) image = me.lockImage;
        var me = this;
        me.islock = !me.islock;
        if (me.islock) {
            image.attr("src", "/assets/js/workflow/images/toolbar/unlock.png");

            me.UnBind();
            myCanvas.dblclick(function (e) {
                mouseOperation.leftbuttondoubleclick(e);
            });
        }
        else {
            me.UnBind();

            this.BindEvent();
            image.attr("src", "/assets/js/workflow/images/toolbar/lock.png");
        }


    },

    UnBind: function () {
        divWorkspace.unbind();
        $(document).unbind("keydown");
        myCanvas.unbind();
    },

    BindEvent: function () {
        var me = this;
        myCanvas.mousedown(function (e) {
            if (e.button == 0) {
                if (e.ctrlKey) {
                    mouseOperation.ctrlKeybuttondown(e);
                }
                else {
                    mouseOperation.leftbuttondown(e);
                }
            }
            else if (e.button = 1) {
                mouseOperation.rightbuttondown(e);
            }


        }).
        mouseup(function (e) {
                if (e.button == 0)
                    mouseOperation.leftbuttonUp(e);
            }
        ).mousemove(function (e) {
            mouseOperation.mouseMove(e);
        });

        var isctrlKey = false;

        $(document).keydown(
            function (e) {
                if (e.keyCode == 17) isctrlKey = true;
                if (isctrlKey && e.keyCode == 90)
                    me.UndoCommand();
                else if (isctrlKey && e.keyCode == 89)
                    me.RedoCommand();
                else {
                    switch (e.keyCode) {
                        case 46:
                            if (selectedObjects.length > 0) {
                                $.each(selectedObjects, function (i, val) {
                                    val.Dispose();
                                });
                                selectedObjects = new Array();
                            }
                            else if (gcommand == Command.SelectActivity)
                                currentActivity.Dispose();
                            else if (gcommand == Command.SelectRule)
                                currentRule.Dispose();
                            break;
                        case 38:
                            if (selectedObjects.length > 0) {
                                $.each(selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X, val.position.Y - 1), true);
                                });
                            }
                            else if (gcommand == Command.SelectActivity)
                                currentActivity.MoveActivity(new Point(currentActivity.position.X, currentActivity.position.Y - 1), true);
                            return false;

                        case 40:
                            if (selectedObjects.length > 0) {
                                $.each(selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X, val.position.Y + 1), true);
                                });
                            }
                            else if (gcommand == Command.SelectActivity)
                                currentActivity.MoveActivity(new Point(currentActivity.position.X, currentActivity.position.Y + 1), true);
                            return false;
                        case 37:
                            if (selectedObjects.length > 0) {
                                $.each(selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X - 1, val.position.Y), true);
                                });
                            }
                            else if (gcommand == Command.SelectActivity)
                                currentActivity.MoveActivity(new Point(currentActivity.position.X - 1, currentActivity.position.Y), true);
                            return false;
                        case 39:
                            if (selectedObjects.length > 0) {
                                $.each(selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X + 1, val.position.Y), true);
                                });
                            }
                            else if (gcommand == Command.SelectActivity)
                                currentActivity.MoveActivity(new Point(currentActivity.position.X + 1, currentActivity.position.Y), true);
                            return false;

                    }
                }
            }
        );
        divWorkspace.keyup(function () {
            ctrlKey = false;
        })


        myCanvas.dblclick(function (e) {
            mouseOperation.leftbuttondoubleclick(e);
        });


    },

    Load: function (tmp, isImport) {
        template = tmp;
        if (template.templateName) {
            $("#divTemplateName").css({
                'display': 'block',
                'left': (divWorkspace.width() - $("#divTemplateName").width()) / 2
            });
            $("#divTemplateName").html(template.templateName);

        }
        else $("#divTemplateName").css('display', 'none');


        if (activityHelper == undefined)
            activityHelper = new ActivityHelper();
        else {
            activityHelper.Dispose();
            activityHelper = new ActivityHelper();
        }


        $.each(template.activities, function (i, val) {
            if (val.isDel == 0) {
                var activity_coordinate = val.coordinate.split('$');
                var position = new Point(activity_coordinate[0], activity_coordinate[1]);
                var activity = activityHelper.AddActivity(position, val.activityType, true);
                activity.id = val.id;
                if (val.activityType == ActivityType.Start)
                    activityHelper.StartActivity = activity;
                else if (val.activityType == ActivityType.End)
                    activityHelper.EndActivity = activity;
                else if (val.activityType == ActivityType.Drafting)
                    activityHelper.DraftingActivity = activity;

                activity.isSelect = 0;
                val.guid = activity.guid;
                val.insert = 0;
                activity.SetProperty(val);
                activity.ResetActivity();
            }
        });

        $.each(template.rules, function (i, val) {
            if (val.isDel == 0) {
                val.insert = 0;
                var activity = activityHelper.Activitys.where(val.fromGuid || val.fromActivityId, 'id');
                if (val.ruleType == 0) {
                    if (activity != null) {
                        var rule = new Rule(activity);
                        var position = val.coordinate.split(',');
                        var positionX = position[0].split('$');
                        var positionY = position[1].split('$');
                        if (positionX.length > 2)
                            for (j = 1; j < positionX.length - 1; j++) {
                                rule.AddPoint(new Point(positionX[j], positionY[j]));
                            }
                        var endac = activityHelper.Activitys.where(val.toActivityId || val.fromActivityId, 'id');
                        canvasHelper.AddRule(rule, endac, true);

                        rule.SetProperty(val);
                    }


                }
                else if (!isImport) {
                    if (activity.ActivityProperty.WF_RULE == undefined)
                        activity.ActivityProperty.WF_RULE = new Array();
                    activity.ActivityProperty.WF_RULE[activity.ActivityProperty.WF_RULE.length] = val;

                }
            }
        });

        $.each(activityHelper.Activitys, function (i, val) {
            if (val.activityType == ActivityType.Merging) {
                var branchActivityId = activityHelper.Activitys.where(val.ActivityProperty.branchActivityId);
                val.BranchingControl = branchActivityId;
                branchActivityId.MergingControl = val;
            }
        })


    },

    HistroyOpertion: function () {
        var me = this;
        var tmp = {};
        tmp.id = OrgID;
        tmp.templateName = template.templateName == undefined ? '' : template.templateName;
        tmp.description = template.description == undefined ? '' : template.description;
        HistroyOpertion[HistroyOpertion.length] = me.Snapshot(tmp);
    },

    UndoCommand: function () {
        var me = this;
        var arraylength = HistroyOpertion.length;
        if (arraylength > 1) {
            --arraylength;
            NextOpertion[NextOpertion.length] = HistroyOpertion[arraylength];
            HistroyOpertion.splice(arraylength, 1);
            me.Load($.evalJSON(HistroyOpertion[--arraylength]));
        }
    },

    RedoCommand: function () {
        var me = this;
        var arraylength = NextOpertion.length;
        if (arraylength > 0) {
            --arraylength;
            var jsString = NextOpertion[arraylength];
            NextOpertion.splice(arraylength, 1);
            HistroyOpertion[HistroyOpertion.length] = jsString;
            me.Load($.evalJSON(jsString));
        }
    },

    Export: function () {
        var me = this;
        var tmp = {};
        tmp.id = OrgID;
        tmp.templateName = template.templateName == undefined ? '' : template.templateName;
        tmp.description = template.description == undefined ? '' : template.description;
        var temp = $.base64.btoa(me.Snapshot(tmp));
        var blobBuilder;
        //var Data = initialData(, $.toJSON({  }));

        $.AjaxRequest('Workflow_Output', {"Template": me.Snapshot(tmp)}, function (data) {
            temp = data;
            var blobObject = new Blob([temp], 'UTF-8');
            var name = tmp.templateName == undefined || tmp.templateName.length > 0 ? "模版" + '.template' : tmp.templateName + '.template'
            window.navigator.msSaveBlob(blobObject, name);
        });

        //$.ajax({
        //    async: false,
        //    cache: false,
        //    type: 'post',
        //    dataType: "json",
        //    data: { RequestData: Data },
        //    url: "/Handlers/Do.ashx",
        //    error: function () {
        //        alert('请求失败');
        //    },
        //    success: function (data) {

        //    }
        //});


    },

    Import: function () {
        var me = this;
        $("#import").unbind();
        me.CanOperation = true;

        $("#import").bind("change", function () {
            var file = this.files[0];
            var reader = new FileReader();
            reader.readAsText(file, 'UTF-8');
            reader.onload = function (e) {
                $.base64.utf8encode = true;

                var temp = $.evalJSON($.base64.atob(reader.result, true));

                OrgID = temp.id;

                if (OrgID == undefined) {
                    var me = this;
                    var layerNum = $.layer({
                        type: 1,
                        title: false,
                        move: [$("#divorgTitle"), true],
                        fix: false,
                        closeBtn: true,
                        shadeClose: false,
                        shade: [0.5, '#000', true],
                        border: [5, 0.3, '#666', true],
                        offset: ['50%', '50%'],
                        area: ['360px', '420px'],
                        page: {dom: $("#divOrg")},
                        success: function () {
                        }
                    });
                    $(".xubox_main").css("background-color", "transparent");
                    OrgHelper.BindOrg(SqlHelper.OrgList);
                    $("#btnCreateOK").unbind();
                    $("#btnCreateCancel").unbind();
                    $("#btnCreateOK").click(function () {

                        var nodes = zTreeObj.getSelectedNodes();
                        if (nodes.length > 0) {
                            OrgID = nodes[0].ID;
                            SqlHelper.GetAllJob();


                            $.each(temp.activities, function (i, val) {
                                for (i in ActivityPropertyStatus) {
                                    var option = ActivityPropertyStatus[i];
                                    var op = option.split('|');
                                    op[0] = parseInt(op[0]);
                                    op[1] = parseInt(op[1]);
                                    var tmp = (activity.ActivityProperty[i] << op[0]);
                                    activity.ActivityProperty.status |= tmp;
                                }
                            })


                            me.Load(temp, true);
                            templateStatus = TemplateStatus.Import;
                        }
                    });
                    $("#btnCreateCancel").click(function () {
                        layer.close(layerNum);
                    });


                }
                else {

                    SqlHelper.GetAllJob();
                    ToolBar.Load(temp, true);
                    templateStatus = TemplateStatus.Import;
                }
            }

        });
        $("#import").click();

    }
}
